import { getRepository, Like, Repository } from 'typeorm';
import { Rcontext } from '../..';
import jwt from 'jsonwebtoken';
import User from '../../entity/user';
import { secret } from '../../config/app';

const UserController = {
  // 获取用户列表
  async getUserList(ctx: Rcontext) {
    const userRepository = getRepository(User);
    // 获取所有
    const [list, count] = await userRepository.findAndCount({
      select: ['name', 'major'], // 查询的字段
      skip: 2, // 跳过的数量
      take: 4, // 查询的数量
      // 排序
      order: {
        age: 'DESC',
      },
      // where: {
      //   name: Like('%l%'),
      // },
    });

    ctx.send({
      list,
      count,
    });
  },
  // 使用querybuilder查询，更灵活，可以打印出sql语句
  async getUserByQueryBuilder(ctx: Rcontext) {
    const userRepository: Repository<User> = getRepository(User);

    const qb = userRepository.createQueryBuilder('account');

    // 选择
    // qb.select(`
    // account.id as id,
    // account.name as name,
    // account.age as age,
    // account.major as major
    // `);

    // 模糊查询
    // qb.where('user.name LIKE :name ', {
    //   name: '%e%',
    // });

    // 分页
    // qb.skip(2).take(2)

    // 排序
    // qb.orderBy('age', 'DESC');

    // groupBy
    // qb.select('major')
    // qb.groupBy('major')

    // distinct
    qb.select(`major`).distinct(true);

    // getRawMany获取原数数据，getCount获取数量
    const [list, count] = await Promise.all([qb.getRawMany(), qb.getCount()]);
    ctx.send({
      list,
      count,
      sql: qb.getSql(), // 打印sql语句
    });
  },
  // 新增用户
  async addUser(ctx: Rcontext) {
    const userRepository = getRepository(User);
    const { body } = ctx.request;

    const userToBeSaved = new User();
    userToBeSaved.name = body.name;
    userToBeSaved.age = body.age;
    userToBeSaved.major = body.major;
    userToBeSaved.password = body.password;

    const result = await userRepository.save(userToBeSaved);
    ctx.send(result);
  },
  // 更新用户
  async updateUser(ctx: Rcontext) {
    const userRepository = getRepository(User);
    const { body } = ctx.request;

    const result = await userRepository.update(body.id, body);
    ctx.send(result);
  },
  // 删除用户
  async deleteUser(ctx: Rcontext) {
    const userRepository = getRepository(User);
    const { body } = ctx.request;

    const result = await userRepository.delete(body.id);

    ctx.send(result);
  },
  async login(ctx: Rcontext) {
    const userRepository = getRepository(User);
    const data: {
      name: string;
      password: string;
    } = ctx.request.body;

    // 通过用户名、密码找到登录用户
    const user = await userRepository.findOne({
      where: {
        name: data.name,
        password: data.password,
      },
    });

    if (!user) {
      ctx.sendError({}, undefined, '用户不存在');
      return;
    }

    // 通过jsonwebtoken生成token，传给前端自行保存，前端需要在header中带过来
    const result = {
      token: jwt.sign({ id: user.id }, secret, { expiresIn: '3d' }),
      userInfo: user,
    };
    ctx.send(result);
  },
  // 获取用户信息
  async getUserInfo(ctx: Rcontext) {
    // id通过koa-jwt注入，在ctx.state上获取，jwtData为koa-jwt配置的key
    const { id } = ctx.state.jwtData;
    console.log(ctx.state.jwtData); // { id: 3, iat: 1642734531, exp: 1642993731 }
    const userRepository = getRepository(User);

    const user = await userRepository.findOne(id);

    ctx.send(user);
  },
};

export default UserController;
